<template>
    <div class="view">
        <nav-bar title="发表评论" :fixed="false" backgroundColor="#f9f9f9">
            <div class="back" slot="left" @click="back">
                <i class="iconfont icon-fanhui"></i>
            </div>
            <div class="submit" slot="right" @click="submit">
                发布
            </div>
        </nav-bar>
        <cube-scroll :data="orderList" class="comment-scroll">
            <div class="order-item" v-for="(comment,index) in commentList" :key="index">
                <div class="order-rate">
                    <img class="order-img" :src="comment.image+'?imageView2/0/w/100'">
                    <div class="order-star">
                        <cube-checker :options="checkerOptions" type="radio" v-model="comment.score">
                            <cube-checker-item v-for="item in checkerOptions" :key="item.value" :option="item">
                                <div class="order-star-item"><i :class="'iconfont '+item.font"></i>{{item.text}}</div>
                            </cube-checker-item>
                        </cube-checker>
                    </div>
                </div>
                <textarea ref="textarea" class="order-textarea" v-model="comment.content" placeholder="这件宝贝是否满足你的期待？说说你的使用感受，分享给一样想买这件宝贝的TA们吧!"></textarea>
                <div class="order-upload">
                    <!--                    v-if="device.status"-->
                    <cube-upload v-if="!device.status" v-model="comment.valueList" :action="uploadOption" :max="9" :simultaneous-uploads="1" @files-added="filesAdded"/>
                    <!--                   -->
                    <div class="app-order-upload clear-fix" v-else>
                        <div class="app-order-upload-btn" v-if="comment.valueList.length <= 9" @click="appOrderUpload(index)"></div>
                        <div class="app-order-upload-show" v-for="(value,num) in comment.valueList" v-if="value.response" :style="`background-image:url(${value.response.data.file_path});`">
                            <i class="cubeic-wrong" @click="deletePhoto(index,num)"></i>
                        </div>
                    </div>
                </div>
            </div>
        </cube-scroll>
    </div>

</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";
    import DialogConfig from "@/constant/DialogConfig";
    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";

    import NavBar from "@/components/aui/NavBar.vue";

    import CommonUnit from "@/unit/CommonUnit";

    @Component({
        components: {
            NavBar
        }
    })
    export default class OrderComment extends Scene {

        @State("DeviceStore")
        private device!: any;

        private orderList: any[] = [];
        private checkerOptions: any[] = [{
            value: 30,
            text: "好评",
            font: "icon-goodevaluation"
        }, {
            value: 20,
            text: "中评",
            font: "icon-poorevaluation"
        }, {
            value: 10,
            text: "差评",
            font: "icon-poorevaluation"
        }];
        private commentList: any[] = [];

        @State("UserStore")
        private user!: InterfaceUser;

        private back(): void {
            this.navigateBack();
        }

        private get orderId(): string {
            return String(this.$route.query.orderId || "");
        }

        private get uploadOption(): any {
            let uploadOption: any = {};
            uploadOption.target = this.api.imageUpload;
            uploadOption.fileName = "iFile";
            uploadOption.data = {type: "photo"};
            uploadOption.headers = {token: this.user.token};
            uploadOption.checkSuccess = (res: any, file: any) => {
                return res.code === 1;
            };
            return uploadOption;
        }

        private mounted() {
            Http.get(this.api.orderComment, {order_id: this.orderId}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    this.orderList = res.data.itemsList;
                    for (let i in res.data.itemsList) {
                        const item: any = {};
                        item.itemId = res.data.itemsList[i].item_id;
                        item.image = res.data.itemsList[i].image ? res.data.itemsList[i].image.file_path : "";
                        item.score = "";
                        item.content = "";
                        item.valueList = [];
                        this.commentList.push(item);
                    }
                } else {
                    if (this.globalSingleResultToast(res)) {
                        setTimeout(() => {
                            this.navigateBack();
                        }, 2500);
                    }
                }
            });
            this.$nextTick(() => {
                window.addEventListener("native.keyboardshow", (event: any) => {
                    setTimeout(() => {
                    }, 300);
                });


                window.addEventListener("native.keyboardhide", () => {
                    console.log("keyboardhide");
                    setTimeout(() => {
                        for (let i in (<any> this).$refs.textarea) {
                            (<any> this).$refs.textarea[i].blur();
                        }
                    }, 300);
                });
            });
        }

        private filesAdded(files: any): void {
            let hasIgnore = false;
            const maxSize = 2 * 1024 * 1024; // 1M
            for (let k in files) {
                const file = files[k];
                if (file.size > maxSize) {
                    file.ignore = true;
                    hasIgnore = true;
                }
            }
            hasIgnore && (<any> this).$createToast({
                type: "warn",
                time: 1000,
                txt: "必须选择不超过2M的照片"
            }).show();
        }

        private get commentParameter(): any[] {
            let commentParameter: any[] = [];
            for (let i in this.commentList) {
                const comment: any = {};
                comment.item_id = this.commentList[i].itemId;
                comment.score = this.commentList[i].score;
                comment.content = this.commentList[i].content;
                comment.image_list = [];
                comment.uploaded = [];
                for (let j in this.commentList[i].valueList) {
                    if (this.commentList[i].valueList[j].response.code === 1) {
                        comment.image_list.push(this.commentList[i].valueList[j].response.data.file_path);
                        comment.uploaded.push(this.commentList[i].valueList[j].response.data.id);
                    }
                }
                commentParameter.push(comment);
            }
            return commentParameter;
        }

        private submit(): void {
            let toast = (<any> this).$createToast({
                txt: "正在发表评价",
                time: 0,
            }).show();
            Http.post(this.api.orderComment, {order_id: this.orderId, formData: JSON.stringify(this.commentParameter)}, {token: this.user.token}).then((res) => {
                toast.hide();
                this.$nextTick(() => {
                    if (res.code === 1) {
                        (<any> this).$createToast({
                            txt: "评价发布成功，正在返回上一页",
                            type: "correct",
                            time: 2500,
                            onTimeout: () => {
                                this.navigateBack();
                            }
                        }).show();
                    } else {
                        this.globalSingleResultToast(res);
                    }
                });

            }).catch(() => {
                toast = (<any> this).$createToast({
                    txt: "评价发布出错，请稍后重试",
                    type: "error",
                    time: 2500
                });
                setTimeout(() => {
                    toast.hide();
                }, 2500);
            });
        }

        private deletePhoto(i: number, j: number) {
            this.commentList[i].valueList.splice(j, 1);
        }

        private appOrderUpload(i: number) {
            for (let i in (<any> this).$refs.textarea) {
                (<any> this).$refs.textarea[i].blur();
            }
            (<any> this).$createActionSheet({
                data: [
                    {
                        content: "从相册中选择",
                        sourceType: "PHOTOLIBRARY"
                    },
                    {
                        content: "拍摄",
                        sourceType: "CAMERA"
                    },

                ],
                onSelect: (item: any, index: any) => {
                    if (this.device.status) {
                        let toast = (<any> this).$createToast({
                            time: 0,
                            txt: item.sourceType === "CAMERA" ? "初始化相机" : "打开系统相册",
                            mask: true
                        }).show();
                        let cameraOptions = {
                            quality: 75,
                            destinationType: Camera.DestinationType.FILE_URI,
                            sourceType: item.sourceType === "CAMERA" ? Camera.PictureSourceType.CAMERA : Camera.PictureSourceType.PHOTOLIBRARY,     //照相机类型
                            allowEdit: true,
                            encodingType: Camera.EncodingType.JPEG,
                            saveToPhotoAlbum: false,
                            cameraDirection: "BACK"
                        };
                        (<any> navigator).camera.getPicture((img: string) => {
                            Http.uploadNative(this.api.imageUpload, img, {type: "header"}, {token: this.user.token}).then((res) => {
                                if (res.code === 1) {
                                    this.commentList[i].valueList.push({response: res});
                                    toast.hide();
                                } else {
                                    toast = (<any> this).$createToast({
                                        time: 2000,
                                        txt: res.msg,
                                        mask: true,
                                        type: "error"
                                    }).show();
                                }
                            }).catch((e: any) => {
                                toast = (<any> this).$createToast({
                                    time: 2000,
                                    txt: "网络出错",
                                    mask: true,
                                    type: "error"
                                }).show();
                            });

                        }, ((error: any) => {
                            toast.hide();
                        }), cameraOptions);
                        toast.hide();
                    }

                }
            }).show();
        }
    }
</script>

<style scoped lang="stylus">
    .view
        width 100vw;
        height 100vh;
        background $theme-page-common-background-color

        .submit
            color $theme-common-color;
            font-size 14px;

        .comment-scroll
            height calc(100vh - 44px - var(--safe-area-inset-top));
            width 100vw;

            .order-item
                margin-bottom 15px;
                background #fff;
                width 100vw;

                .order-rate
                    height 50px;
                    position relative;
                    display flex;
                    padding 0 10px;
                    align-items center;

                    &::after
                        content '';
                        display block;
                        height 1px;
                        position absolute;
                        bottom 0;
                        left 0;
                        right 0;
                        transform scaleY(.5);
                        border-bottom 1px solid #e7e7e7

                    .order-img
                        height 40px;
                        width 40px;
                        display block;
                        border-radius 2px;

                    .order-star
                        height 30px;
                        padding 0 20px;

                        >>> .cube-checker-item
                            padding 0;
                            margin 0;

                            &::after
                                display none !important;

                            .order-star-item
                                width 90px;
                                color #666;
                                display flex;
                                align-items center;
                                height 30px;

                                i
                                    padding-right 6px;
                                    color #444;
                                    font-size 19px;


                        >>> .cube-checker-item_active
                            color $theme-common-color;
                            background #fff;

                            .order-star-item
                                color $theme-common-color;

                                i
                                    color $theme-common-color;

                .order-textarea
                    width 100%;
                    height 85px;
                    border 0 solid #fff;
                    padding 10px;
                    box-sizing border-box;
                    font-size 13px;
                    color #333;

                    &::-webkit-input-placeholder
                        color #ababb3;

                .order-upload
                    height auto;
                    padding 10px;

                    >>> .cube-upload-file-status
                        color $theme-common-color;

                    >>> .cube-upload-btn-def
                        &::after
                            border 1px dashed #666;

                        i
                            position relative;
                            width 100%;
                            height 100%;
                            display block;

                            &::before, &::after
                                font-style normal;
                                background none;
                                transform none;
                                display flex;
                                justify-content center;
                                color #bdbec3;
                                width 100%;
                                left 0;

                            &::before
                                content '\e6ac';
                                font-family "iconfont" !important;
                                align-items flex-end;
                                top 0;
                                height 60%;
                                font-size 26px;

                            &::after
                                content '添加照片';
                                height 30%;
                                top 60%;
                                font-size 12px;
                                align-items center;

    .app-order-upload
        display block;
        position relative;

        .app-order-upload-show, .app-order-upload-btn
            width 80px;
            height 80px;
            background #fff;
            border 1px solid rgba(189, 190, 195, .3);
            position relative;
            margin-right 12px;
            margin-bottom 14px;
            float left;

        .app-order-upload-btn
            color #bdbec3;

            &::before, &::after
                font-style normal;
                background none;
                transform none;
                display flex;
                justify-content center;
                color #bdbec3;
                width 100%;
                left 0;

            &::before
                content '\e6ac';
                font-family "iconfont" !important;
                align-items flex-end;
                top 0;
                height 60%;
                font-size 26px;

            &::after
                content '添加照片';
                height 30%;
                top 60%;
                font-size 12px;
                align-items center;

        .app-order-upload-show
            background-position center;
            background-size cover;

            .cubeic-wrong
                position absolute;
                z-index 2;
                top: -2px;
                right -2px;
                color rgba(0, 0, 0, 0.8);
                font-size 15px;
                background-color #fff;
                border-radius 50%;

                &::before
                    display inline-block;
                    transform scale(1.625)
                    transform-origin center;


</style>
